﻿#include "device.hpp"
#include "db/sqlite_conn.hpp"
#include "service/device_state.hpp"
#include "utils/utils_string.hpp"


#include <math.h>
//#include "wlog.hpp"

namespace bz
{

	

	device::device()
	{
		device_type_vec_ = {
			//{DEVICE_TYPE::SMC,utils_string::ascii_utf8("SMC")},
			{DEVICE_TYPE::TERMINAL,utils_string::ascii_utf8("TERMINAL")},
		};
		
	}

	device::~device()
	{
	}

	void device::init()
	{
		ormpp_auto_key auto_key{
		"id"
		};
		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);
		db->set_auto_key<device>(auto_key);
	}

	std::pair<int, string> device::index(int page, string name, int parent_id)
	{

		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);

		string csql = " `name` like '%" + name + "%' ";

		if (parent_id > 0) {
			csql += "and parent_id =" + to_string(parent_id);
		}
		
		int num = db->count<device>(csql);
		int limit = 10;
		double totalpage = ceil(double(num)/ double(limit));
		if (page < 1) {
			page = 1;
		}
		else if (page > int(totalpage)) {
			page = int(totalpage);
		}
		
		
		string sql = " where `name` like '%" + name + "%' ";
		
		if (parent_id > 0) {
			sql += "and organ_id =" + to_string(parent_id);
		}

		sql += " limit " + to_string(limit) + " offset " + to_string((page-1)*limit);
		auto rows = db->query<device>(sql);
		
		json lists = json::array();
		for (auto it : rows)
		{
			device* d= device_state::instance()->get_device(it.id);
			/*if (it.device_type == 1)
			{
				it.ip = ip_manager::instance()->fsbc_use_ip_;
			}*/
			if (d) {
				it.online_state = d->online_state;
				it.net_ip = d->net_ip;
			}

			
			json row;
			to_json(row, it);
			lists.push_back(row);
		}

		return pair<int, string>(num, lists.dump());
	}

	int device::add()
	{
		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);
		return db->insert(*this);
	}

	bool device::remove()
	{
		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);
		return db->delete_records(FID(device::id), "=", id);
	}

	int device::update()
	{
		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);
		return db->update(*this);
	}

	
	bool device::get()
	{
		auto db = sqlite_conn::get_conn();
		sqlite_guard guard(db);
		auto res = db->query(FID(device::id), "=", id);
		if (res.size() > 0) {
			*this = res[0];
			return true;
		}
		return false;
	}
}